package com.lmaor.project.commons.parameters;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;

import com.alibaba.fastjson.JSON;


public class ParamUtils {
	
	public static Object stringToObject(Class type,String value,Class comType){
		
		if(type == int.class||type==Integer.class){
			return NumberUtils.toInt(value);
		}
		if(type == long.class||type==Long.class){
			return NumberUtils.toLong(value);
		}
		if(type == short.class||type==Short.class){
			return NumberUtils.toShort(value);
		}
		if(type == byte.class||type==Byte.class){
			return (byte)NumberUtils.toInt(value);
		}
		if(type == double.class||type==Double.class){
			return NumberUtils.toDouble(value);
		}
		if(type == float.class||type==Float.class){
			return NumberUtils.toFloat(value);
		}
		if(type == boolean.class||type==boolean.class){
			return "true".equals(value);
		}
		if(type == char.class||type==Character.class){
			return value!=null&&value.length()>0?value.charAt(0):'\0';
		}
		if(value == null){
			return null;
		}
		if(type == BigDecimal.class){
			return new BigDecimal(value);
		}
		if(type == String.class){
			return value;
		}
		if(type == StringBuilder.class){
			return new StringBuilder(value);
		}
		if(type == StringBuffer.class){
			return new StringBuffer(value);
		}
		
		value = value.trim();
		int length = value.length();
		if(length < 2){
			return null;
		}
		char sc = value.charAt(0);
		char ec = value.charAt(length-1);
		if(sc == '{' && ec == '}'){
			return JSON.parseObject(value, type);
		}
		if(sc == '[' && ec == ']'){
			if(List.class.isAssignableFrom(type)){
				if(comType!=null&&comType!=void.class){
					return JSON.parseArray(value, comType);
				}else{
					return JSON.parseArray(value);
				}
			}else{
				List list = JSON.parseArray(value, type.getComponentType());
				Object arrs = Array.newInstance(type.getComponentType(), list.size());
				for (int i = 0; i < list.size(); i++) {
					Array.set(arrs, i, list.get(i));
				}
				return arrs;
			}
		}
		
		return null;
	}
	
	
	
}
